package alo.p4.work;

import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;


//匹配括号
public class IsValid {
    class Solution {
        public boolean isValid(String s) {
            int n = s.length();
            //若括号的个数为奇数，直接返回错误
            if (n % 2 == 1) {
                return false;
            }
            //建立对应的括号匹配的散列表
            Map<Character, Character> pairs = new HashMap<Character, Character>() {{
                put(')', '(');
                put(']', '[');
                put('}', '{');
            }};
            //定义一个栈
            Deque<Character> stack = new LinkedList<Character>();
            //读取字符
            for (int i = 0; i < n; i++) {
                char ch = s.charAt(i);
                //读取到的是后括号
                if (pairs.containsKey(ch)) {
                    //如果栈为空或者栈顶元素不是后括号的匹配
                    if (stack.isEmpty() || stack.peek() != pairs.get(ch)) {
                        return false;
                    }
                    stack.pop();
                } else {
                    stack.push(ch);
                }
            }
            return stack.isEmpty();
        }
    }
}
